//
//  CityWeatherList.m
//  
//
//  Created by Lawrence on 15/9/24.
//
//

#import "CityWeatherList.h"
#import "CtiyCell.h"
#import "WeatherViewController.h"
#import <CoreLocation/CoreLocation.h>  //导入定位库
#import <MBProgressHUD.h>
#import <AFNetworking.h>
#import <UIImageView+AFNetworking.h>
#import "NSUserDefaultsHelper.h"

#define imageUrl @"http://m.weather.com.cn/img/%@"


@interface CityWeatherList ()<CLLocationManagerDelegate,MBProgressHUDDelegate>{
    CLLocationManager *_locationManager;
}
@property(nonatomic,retain) NSDictionary *dictCity;
@property(nonatomic,retain) NSArray *dictCityArry;


@property(nonatomic,strong) UILabel *labCityName;
@property(nonatomic,strong) UILabel *labCityWeather;
@property(nonatomic,strong) UILabel *labTempMax;
@property(nonatomic,strong) UIImageView *imageWeather;
@property(nonatomic,strong) UILabel *labTempMaxAndlabTempMini;
@property(nonatomic,strong) MBProgressHUD *HUD;


@end

@implementation CityWeatherList
-(instancetype)initCityWeatherListWithStoryboard:(NSDictionary *)CityInfo{
    UIStoryboard *stortboard=[UIStoryboard storyboardWithName:@"CityWeather" bundle:nil];
    CityWeatherList *list=[stortboard instantiateViewControllerWithIdentifier:@"CityWeatherList"];
    list.dictCity=CityInfo;
    list.dictCityArry=[CityInfo allKeys];
    return list;
}
#pragma mark 加载xib文件
-(void) registerCellNib{
    UINib *nib=[UINib nibWithNibName:@"CtiyCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:@"CtiyCell"];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initHUD];
    [self registerCellNib];
    [self initNav];
    [self initUI];
    [self initTableViewHeaderView];
    _locationManager.delegate=self;
    //定位管理器
    _locationManager=[[CLLocationManager alloc] init];
    if (![CLLocationManager locationServicesEnabled]) {
        UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:@"提示" message:@"定位不成功，请确认开启定位" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alertView show];
        return;
    }
    //如果没有授权则请求用户授权
    if ([CLLocationManager authorizationStatus]==kCLAuthorizationStatusNotDetermined) {
        [_locationManager requestWhenInUseAuthorization];
    }else if([CLLocationManager authorizationStatus]==kCLAuthorizationStatusAuthorizedWhenInUse){
        //设置代理
        _locationManager.delegate=self;
        //设置定位精度
        _locationManager.desiredAccuracy=kCLLocationAccuracyBest;  //设置千米级别的定位
        CLLocationDistance distance=10.0;   //一千米定位一次
        _locationManager.distanceFilter=distance;
        
        
        //开启定位
        [_locationManager startUpdatingLocation];
       // [MBProgressHUD showHUDAddedTo:self.view animated:YES];
   }
}

-(void)initHUD{
    self.HUD=[[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:_HUD];
    _HUD.delegate=self;
    _HUD.labelText=NSLocalizedString(@"loading",nil);
    _HUD.detailsLabelText=NSLocalizedString(@"loading,please weating",nil);
    _HUD.square=YES;
    
    //[self.HUD show:YES];
    
}
-(void) initTableViewHeaderView{
    
    UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0,0,self.view.frame.size.width, self.view.frame.size.height*.4)];
    [view  setBackgroundColor:[UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:0.8]];
    
    //渐变色
    CAGradientLayer *gradient=[CAGradientLayer layer];
    gradient.frame=view.frame;
    
    gradient.colors=[NSArray arrayWithObjects:
                     (id)[UIColor darkGrayColor].CGColor,
                     (id)[UIColor colorWithRed:0.0 green:122.0/255.0 blue:122.0/255.0 alpha:0.2].CGColor,
                     (id)[UIColor colorWithRed:0.0 green:160.0/255.0 blue:160/255.0 alpha:0.8].CGColor,
                     nil];
    
    [view.layer insertSublayer:gradient atIndex:0];
    self.tableView.tableHeaderView=view;
    
    
    
    self.labCityName=[[UILabel alloc] initWithFrame:CGRectMake(0,view.frame.size.height*.3+60,view.frame.size.width*.4,60)];
    CGPoint centerLabCityName=CGPointMake(self.view.center.x,view.frame.size.height*.3);
    self.labCityName.center=centerLabCityName;
    self.labCityName.textAlignment=NSTextAlignmentCenter;
    self.labCityName.textColor=[UIColor whiteColor];
    self.labCityName.font=[UIFont systemFontOfSize:40.0f];
    
    self.labCityWeather=[[UILabel alloc] initWithFrame:CGRectMake(0,view.frame.size.height*.5+60,view.frame.size.width*.4,60)];
    self.labCityWeather.textAlignment=NSTextAlignmentCenter;
    self.labCityWeather.textColor=[UIColor whiteColor];
    self.labCityWeather.font=[UIFont systemFontOfSize:18.0f];
    CGPoint centerlabCityWeather=CGPointMake(self.view.center.x,view.frame.size.height*.5);
    self.labCityWeather.center=centerlabCityWeather;
    
    
    self.labTempMax=[[UILabel alloc] initWithFrame:CGRectMake(0,view.frame.size.height*8,view.frame.size.width*.4,60)];
    self.labTempMax.textAlignment=NSTextAlignmentCenter;
    self.labTempMax.font=[UIFont systemFontOfSize:45.0];
    CGPoint centerlabTempMax=CGPointMake(self.view.center.x,view.frame.size.height*.8);
    self.labTempMax.center=centerlabTempMax;
    self.labTempMax.textColor=[UIColor whiteColor];
    
    [view addSubview:_labTempMax];
    [view addSubview:_labCityName];
    [view addSubview:_labCityWeather];
    
    //获取保存在手机中的天气信息
    [self readWeatherData];
}
#pragma mark 回调定位方法开启定位服务并且定位
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    CLLocation *location=[locations firstObject]; //取出第一位置
    CLGeocoder *geoCoder=[[CLGeocoder alloc] init];
    [geoCoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        if (placemarks.count>0) {
            //获取数组第一个对象
            CLPlacemark *placemark=[placemarks objectAtIndex:0];
            //获取定位城市信息
            NSString *city=placemark.locality;
            if (city!=nil) {
                
                [self.HUD showWhileExecuting:@selector(GetWeather:) onTarget:self withObject:[_dictCity objectForKey:city] animated:YES];
            }
        }
    }];
    [_locationManager stopUpdatingLocation];  //关闭定位
   }
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dictCityArry.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CtiyCell *cell=[tableView dequeueReusableCellWithIdentifier:@"CtiyCell" forIndexPath:indexPath];
    cell.labCtiyName.text=NSLocalizedString([self.dictCityArry objectAtIndex:indexPath.row],nil);
    cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
    return cell;
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    WeatherViewController *weather=[[WeatherViewController alloc] initWithCityCode:[_dictCity objectForKey:[_dictCityArry objectAtIndex:indexPath.row]]];
    [self.navigationController pushViewController:weather animated:NO];
}

#pragma mark 通过定位获取天气
-(void)GetWeather:(NSString *)code{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        Weather *weather=[WeatherRequest initWithCityCode:code];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (weather!=nil) {
                [self WeatherForHeaderView:weather];
                [_imageWeather setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:imageUrl,weather.img1]]];
                //[MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                [self.HUD hide:YES];
            }
        });
    });
}

-(void)WeatherForHeaderView:(Weather *) weather{
    [self.labCityName setText:weather.city];
    [self.labCityWeather setText:weather.weather];
    [self.labTempMax setText:weather.temp1];
}
-(void)initNav{
    UIBarButtonItem *leftItem=[[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"返回",nil) style:UIBarButtonItemStylePlain target:self action:@selector(goBack)];
    self.navigationController.navigationItem.leftBarButtonItem=leftItem;
}
-(void)goBack{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)initUI{
    self.tableView.backgroundColor=[UIColor clearColor];
}

-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    [UIView beginAnimations:nil context:nil];
    
    [UIView setAnimationCurve:UIViewAnimationCurveLinear];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDuration:3];
    self.tableView.tableHeaderView.backgroundColor=[UIColor yellowColor];
    
    [UIView commitAnimations];
}

-(void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    
    [self saveWeatherData];
}

#pragma mark 保存天气数据
-(void)saveWeatherData{
    
    if (self.labCityName.text!=nil&&self.labCityWeather.text!=nil&&self.labTempMax.text!=nil) {
        
        NSArray *array=@[
                         self.labCityName.text,
                         self.labCityWeather.text,
                         self.labTempMax.text
                         ];
        
        NSArray *arryName=@[
                            @"city",
                            @"weather",
                            @"temp1"
                            ];
        NSMutableDictionary *dict=[[NSMutableDictionary alloc] initWithObjects:array forKeys:arryName];
        
        NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
        //写入数据
        [NSUserDefaultsHelper writeDataforUserDefaults:user andData:dict];
        
    }
}

-(void)readWeatherData{
    
    NSArray *arryName=@[
                        @"city",
                        @"weather",
                        @"temp1"
                        ];
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    NSMutableArray *arrayWeaterInfo=[NSUserDefaultsHelper readerDataforUserDefaults:user forKey:arryName];
    if ([arrayWeaterInfo count]) {
        
        NSMutableDictionary *dict=[[NSMutableDictionary alloc] initWithObjects:arrayWeaterInfo forKeys:arryName];
        Weather *weather=[[Weather alloc] initWeather:dict];
        [self WeatherForHeaderView:weather];
        
    }
    
}
@end
